package handlers

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"kubeInstall/model"
	"net/http"
)

func AddCredential(r *restful.Request, resp *restful.Response) {

	var req model.Credential
	if err := r.ReadEntity(&req); err != nil {
		RenderError(resp, fmt.Sprintf("read Credential from http body failed,error is  %v\n", err), http.StatusBadRequest)
		return
	}

	// 判断name是否存在，如果存在则返回插入失败
	if exist := req.CheckNameIsExist(req.Name); exist {
		RenderError(resp, fmt.Sprintf("name: %s already exist", req.Name), http.StatusBadRequest)
		return
	}

	//插入数据
	if err := req.AddCredential(); err != nil {
		RenderError(resp, fmt.Sprintf("create Credential failed! error is  %v\n", err), http.StatusBadRequest)

		return
	}

	//查询返回结果
	result, err := req.GetCredentialDetails(req.Name)
	if err != nil {
		RenderError(resp, "get Credential failed", http.StatusInternalServerError)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, result, restful.MIME_JSON)

}

func ListCredential(r *restful.Request, resp *restful.Response) {
	var cred model.Credential
	result, err := cred.GetCredentials()
	if err != nil {
		RenderError(resp, fmt.Sprintf("list Credential failed! error is  %v\n", err), http.StatusInternalServerError)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, result, restful.MIME_JSON)

}

func DeleteCredential(r *restful.Request, resp *restful.Response) {
	var cred model.Credential
	name := r.QueryParameter("name")
	//检查name 是否合法
	//查询数据库name是否存在
	if exist := cred.CheckNameIsExist(name); !exist {
		RenderError(resp, fmt.Sprintf("name : %s not found", name), http.StatusBadRequest)
		return
	}

	if err := cred.DeleteCredential(name); err != nil {
		RenderError(resp, fmt.Sprintf("delete Credential failed! error is  %v\n", err), http.StatusInternalServerError)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, SuccessResp{
		StatusCode: http.StatusOK,
		Message:    fmt.Sprintf("Delete %s Success ", name),
	}, restful.MIME_JSON)
}
